package cn.blue.org.service.impl;
import cn.blue.base.service.BaseService;
import cn.blue.base.service.impl.BaseServiceImpl;
import cn.blue.org.domain.Department;
import cn.blue.org.domain.Employee;
import cn.blue.org.mapper.DepartmentMapper;
import cn.blue.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService{
    @Autowired
    private DepartmentMapper departmentMapper;
    @Override
    public List<Department> findAll() {
        List<Department> result = new ArrayList<>();
        List<Department> all = departmentMapper.findAll();
        if(CollectionUtils.isEmpty(all)){
            return result;

        }
        //stream
        Map<Long, Department> parentMap = all.stream().collect(Collectors.toMap(Department::getId, e -> e));
        for (Department dept : all) {
            if (null == dept.getParentId()){
                //他就是最大的那个die
                result.add(dept);
            } else {
                // 当前的这个dept是个儿子
                // 我爹 自己是个儿子 有爹的id
                Department parent = parentMap.get(dept.getParentId());
                if(null == parent){
                    break;
                }
                List<Department> children = parent.getChildren();
                children.add(dept);
            }
        }

        return result;
    }

    @Override
    public List<Employee> findByDId(Long id) {
        return departmentMapper.findByDId(id);
    }
}



